#!/bin/bash
# xtrabackup 自动备份 MySQL 5.7/8.0 通用脚本
# 支持全量/增量备份，备份保留7天，参数化配置

# ================== 参数区 ===================
# 备份目录（建议使用绝对路径）
BACKUP_DIR="/data/mysql_backup"
# MySQL 连接参数
MYSQL_HOST="127.0.0.1"
MYSQL_PORT="3306"
MYSQL_USER="backupuser"
MYSQL_PASSWORD="password"
# 备份保留天数
KEEP_DAYS=7
# 全量备份时间点（每天几点，24小时制）
FULL_BACKUP_HOUR=2
# xtrabackup 可执行文件路径
XTRABACKUP_BIN="xtrabackup"
# 日志文件
LOG_FILE="$BACKUP_DIR/xtrabackup_backup.log"

# ================== 函数区 ===================
log() {
  echo "[$(date '+%F %T')] $1" | tee -a "$LOG_FILE"
}

get_mysql_version() {
  VER=$($XTRABACKUP_BIN --version 2>/dev/null)
  if [[ -z "$VER" ]]; then
    log "xtrabackup 未安装或不可用！"; exit 1
  fi
  MYSQL_VER=$(mysql -h$MYSQL_HOST -P$MYSQL_PORT -u$MYSQL_USER -p$MYSQL_PASSWORD -e 'select version();' 2>/dev/null | grep -Eo '^[0-9]+\\.[0-9]+')
  echo $MYSQL_VER
}

get_last_full_backup_dir() {
  ls -dt $BACKUP_DIR/full_* 2>/dev/null | head -1
}

# 清理过期备份
delete_old_backups() {
  find $BACKUP_DIR -maxdepth 1 -type d -mtime +$KEEP_DAYS -name 'full_*' -exec rm -rf {} +
  find $BACKUP_DIR -maxdepth 1 -type d -mtime +$KEEP_DAYS -name 'inc_*' -exec rm -rf {} +
}

# ================== 主流程 ===================
mkdir -p "$BACKUP_DIR"
delete_old_backups

HOUR=$(date +%H)
DATE=$(date +%F_%H-%M-%S)
MYSQL_VER=$(get_mysql_version)

# 判断认证参数
if [[ "$MYSQL_VER" == 8.* ]]; then
  PASS_ARG="--password=$MYSQL_PASSWORD"
else
  PASS_ARG="-p$MYSQL_PASSWORD"
fi

# 判断是否做全量备份
if [[ "$HOUR" == "$FULL_BACKUP_HOUR" ]]; then
  BACKUP_TYPE="full"
  BACKUP_PATH="$BACKUP_DIR/full_$DATE"
  log "开始全量备份: $BACKUP_PATH"
  $XTRABACKUP_BIN --backup --host=$MYSQL_HOST --port=$MYSQL_PORT --user=$MYSQL_USER $PASS_ARG --target-dir=$BACKUP_PATH &>> $LOG_FILE
  if [[ $? -eq 0 ]]; then
    log "全量备份完成: $BACKUP_PATH"
  else
    log "全量备份失败: $BACKUP_PATH"; exit 1
  fi
else
  # 增量备份
  LAST_FULL=$(get_last_full_backup_dir)
  if [[ -z "$LAST_FULL" ]]; then
    log "未找到全量备份，先执行一次全量备份！"; exit 1
  fi
  BACKUP_TYPE="inc"
  BACKUP_PATH="$BACKUP_DIR/inc_$DATE"
  log "开始增量备份: $BACKUP_PATH 基于 $LAST_FULL"
  $XTRABACKUP_BIN --backup --host=$MYSQL_HOST --port=$MYSQL_PORT --user=$MYSQL_USER $PASS_ARG --target-dir=$BACKUP_PATH --incremental-basedir=$LAST_FULL &>> $LOG_FILE
  if [[ $? -eq 0 ]]; then
    log "增量备份完成: $BACKUP_PATH"
  else
    log "增量备份失败: $BACKUP_PATH"; exit 1
  fi
fi

# 校验备份完整性
log "校验备份完整性: $BACKUP_PATH"
$XTRABACKUP_BIN --prepare --apply-log-only --target-dir=$BACKUP_PATH &>> $LOG_FILE
if [[ $? -eq 0 ]]; then
  log "备份校验通过: $BACKUP_PATH"
else
  log "备份校验失败: $BACKUP_PATH"; exit 1
fi

exit 0
